<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" :inline="true">
                <el-form-item label="办公楼名称">
                    <el-input v-model="searchInfo.buildingName"></el-input>
                </el-form-item>
                <el-form-item label="项目名称">
                    <el-input v-model="searchInfo.name"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="plus" @click="addUnit">新增申报</el-button>
            </div>
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="办公楼名称" prop="buildingName" show-overflow-tooltip
                    v-if="checkedColumns.includes('办公楼名称')"></el-table-column>
                <el-table-column align="left" label="项目名称" prop="name" show-overflow-tooltip
                    v-if="checkedColumns.includes('项目名称')"></el-table-column>
                <el-table-column align="left" label="申请时间" v-if="checkedColumns.includes('申请时间')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.applyAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="提交状态" v-if="checkedColumns.includes('提交状态')">
                    <template #default="scope">
                        <span>{{ scope.row.submitStatus == 1 ? '已提交' : '待提交' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="审批状态" v-if="checkedColumns.includes('审批状态')">
                    <template #default="scope">
                        <span>{{ scope.row.examineStatus == 1 ? '已审批' : '未审批' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="审批结果" prop="contactUs" v-if="checkedColumns.includes('审批结果')">
                    <template #default="scope">
                        <span>{{ scope.row.examineResult==1?'通过':'未通过' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="附件" v-if="checkedColumns.includes('附件')">
                    <template #default="scope">
                        <span style="color: #3b82f6;cursor: pointer;" @click="seeFile(scope.row.id)">查看</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="操作" v-if="checkedColumns.includes('操作')" min-width="100">
                    <template #default="scope">
                        <el-button type="primary" link icon="edit" v-if="scope.row.submitStatus == 0"
                            @click="editUnit(scope.row)">
                            编辑
                        </el-button>
                        <el-button type="primary" link @click="seeDetail(scope.row)">
                            详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>

        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose"
            :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialogTitle }}</span>
                </div>
            </template>
            <el-form v-if="dialogFormVisible" ref="bangongquForm" label-width="180" :model="form1" :rules="rules">
                <div class="section-title">基本信息</div>
                <el-form-item label="项目名称" prop="name">
                    <el-input v-model="form1.name" placeholder="请输入" style="width: 400px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：多栋办公楼维修项目名称必须一致</span>
                </el-form-item>
                <el-form-item label="维修办公楼" prop="buildingId">
                    <el-select v-model="form1.buildingId" placeholder="请选择" style="width: 400px;">
                        <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <span style="margin-left: 4px;color: #FF473E;">注：请选择办公楼</span>
                </el-form-item>
                <el-form-item label="改变类型" prop="changeType">
                    <el-radio-group v-model="form1.changeType" class="ml-4">
                        <el-radio :value="1" size="large">改变布局和用途</el-radio>
                        <el-radio :value="2" size="large">改变布局</el-radio>
                        <el-radio :value="3" size="large">改变用途</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系人" prop="contacts">
                    <el-input v-model="form1.contacts" placeholder="请输入" style="width: 400px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：如不一致请更改</span>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactUs">
                    <el-input v-model="form1.contactUs" placeholder="请输入" style="width: 400px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：如不一致请更改</span>
                </el-form-item>
                <el-form-item label="变更情况说明" prop="notes">
                    <el-input v-model="form1.notes" type="textarea" :rows="3" placeholder="请输入" style="width: 400px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：说明变更原因和理由</span>
                </el-form-item>
                <div class="section-title" v-if="form1.changeType == 1 || form1.changeType == 2">上传附件</div>
                <el-form-item v-if="form1.changeType == 1 || form1.changeType == 2" label="变更前楼层房间布局图" prop="bgq"
                    style="align-items: normal;">
                    <el-upload ref="uploadRef" v-model:file-list="fileList1" :action="adminUrl"
                        :on-success="uploadSuccess1" :headers="headerOdj">
                        <el-button type="primary">选择文件</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item v-if="form1.changeType == 1 || form1.changeType == 2" label="变更后楼层房间布局图" prop="bgh"
                    style="align-items: normal;">
                    <el-upload ref="uploadRef" v-model:file-list="fileList2" :action="adminUrl"
                        :on-success="uploadSuccess2" :headers="headerOdj">
                        <el-button type="primary">选择文件</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="" style="margin-top: 100px;">
                    <el-button type="primary" @click="enterDialog(0)">保存</el-button>
                    <el-button type="primary" @click="enterDialog(1)">保存并提交</el-button>
                    <el-button @click="closeDialog">关闭</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <el-drawer v-model="dialog3" :size="1000" :before-close="handleClose3" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">查看附件</span>
                    <div>
                        <el-button @click="closeDialog3">取消</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="fjList" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="文件名" prop="fileName">
                </el-table-column>
                <el-table-column align="left" label="文件类型">
                    <template #default="scope">
                        {{ fileTypes[scope.row.fileType] }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="上传时间">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link icon="download" @click="download(scope.row)">
                            下载
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>

        <el-drawer v-model="detailVisible" :size="1000" :before-close="handleCloseDetail"
            :show-close="false" class="sb-draw">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">详情</span>
                    <div>
                        <el-button @click="detailVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="detailVisible" label-width="180" disabled>
                <div class="section-title">基本信息</div>
                <el-form-item label="项目名称" prop="name">
                    <el-input v-model="form2.name" placeholder="请输入" style="width: 350px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：多栋办公楼维修项目名称必须一致</span>
                </el-form-item>
                <el-form-item label="维修办公楼" prop="buildingId">
                    <el-select v-model="form2.buildingId" placeholder="请选择" style="width: 350px;">
                        <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <span style="margin-left: 4px;color: #FF473E;">注：请选择办公楼</span>
                </el-form-item>
                <el-form-item label="改变类型" prop="changeType">
                    <el-radio-group v-model="form2.changeType" class="ml-4">
                        <el-radio :value="1" size="large">改变布局和用途</el-radio>
                        <el-radio :value="2" size="large">改变布局</el-radio>
                        <el-radio :value="3" size="large">改变用途</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系人" prop="contacts">
                    <el-input v-model="form2.contacts" placeholder="请输入" style="width: 350px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：如不一致请更改</span>
                </el-form-item>
                <el-form-item label="联系电话" prop="contactUs">
                    <el-input v-model="form2.contactUs" placeholder="请输入" style="width: 350px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：如不一致请更改</span>
                </el-form-item>
                <el-form-item label="变更情况说明" prop="notes">
                    <el-input v-model="form2.notes" type="textarea" :rows="3" placeholder="请输入" style="width: 350px;" />
                    <span style="margin-left: 4px;color: #FF473E;">注：说明变更原因和理由</span>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    buildingAll
} from '@/api/unit'
import {
    optionList,
    declareMediumApply,
    declareMedium,
    declareMediumFile,
    declareMediumDetail,
    applyEdit
} from '@/api/yewuguanli'

import { reactive, ref, onMounted, computed } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { buildTimeList, countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { Document, Memo } from '@element-plus/icons-vue'
import { formatTimestamps } from '@/utils/format'
import { fileTypes, adoptList } from '@/utils/constant';
defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()

const searchInfo = ref({
    buildingName: '',
    name: '',
    type: 3
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
let validate1 = (rule, value, callback) => {
    if (fileList1.value.length == 0) {
        callback(new Error('请上传文件'))
    } else {
        callback()
    }
}
let validate2 = (rule, value, callback) => {
    if (fileList2.value.length == 0) {
        callback(new Error('请上传文件'))
    } else {
        callback()
    }
}
const rules = reactive({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    buildingId: [{ required: true, message: '请选择办公楼', trigger: 'change' }],
    changeType: [{ required: true, message: '请选择办公楼', trigger: 'change' }],
    contacts: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    contactUs: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    notes: [{ required: true, message: '请输入变更情况说明', trigger: 'blur' }],
    bgq: [{ required: true, validator: validate1, trigger: 'change' }],
    bgh: [{ required: true, validator: validate2, trigger: 'change' }]
})
let validatePass = (rule, value, callback) => {
    callback()
}

const rules2 = reactive({
    name: [{ required: true, validator: validatePass, trigger: 'blur' }],
    profile: [{ required: true, validator: validatePass, trigger: 'blur' }],
    funding: [{ required: true, validator: validatePass, trigger: 'blur' }],
    estimates: [{ required: true, validator: validatePass, trigger: 'blur' }]
})
const active = ref(2)

const totalNum = computed(() => {
    return form1.value.declareDetail.reduce((prev, next) => prev + Number(next.funding), 0)
})

const estimatesNum = computed(() => {
    return form1.value.declareDetail.reduce((prev, next) => prev + Number(next.estimates), 0)
})

const form1 = ref({
    buildingId: '',
    name: '',
    changeType: 1,
    contactUs: '',
    contacts: '',
    estimates: '',
    notes: '',
    totalFunding: '',
    type: 3,
    year: new Date().getFullYear(),
    declareFile: [],
    submitStatus: 0
})

const initForm = () => {
    bangongquForm.value.resetFields()
    form1.value = {
        buildingId: '',
        name: '',
        changeType: 1,
        contactUs: '',
        contacts: '',
        estimates: '',
        notes: '',
        totalFunding: '',
        type: 3,
        year: new Date().getFullYear(),
        declareFile: [],
        submitStatus: 0
    }
    fileList1.value = []
    fileList2.value = []
}

const checkedColumns = ref(['序号', '办公楼名称', '项目名称', '匡算合计', '单项工程综合概算合计', '配置时间', '申请时间', '提交状态', '审批状态', '审批结果', '附件', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).pzwxsq) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).pzwxsq
}
const columns = ref(['序号', '办公楼名称', '项目名称', '匡算合计', '单项工程综合概算合计', '配置时间', '申请时间', '提交状态', '审批状态', '审批结果', '附件', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.pzwxsq = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}

const isEdit = ref(false)
const dialogTitle = ref('改变房屋布局用途申报')
const addUnit = () => {
    dialogTitle.value = '改变房屋布局用途申报'
    isEdit.value = false
    dialogFormVisible.value = true
}
function editUnit(row) {
    declareMediumDetail(row.id).then(res => {
        form1.value = row
        form1.value.checkOptions = res.result.map(item => item.checkOptionId)
        form1.value.declareDetail = res.result
        form1.value.declareId = row.id
        declareMediumFile(row.id).then(res2 => {
            if (res2.result.length > 0) {
                res2.result.forEach(item => {
                    if (item.fileType == 11) {
                        fileList1.value = [
                            {
                                name: item.fileName,
                                url: item.fileUrl,
                                response: { result: item.fileUrl },
                                fileType: 11
                            }
                        ]
                    }
                    if (item.fileType == 12) {
                        fileList2.value = [
                            {
                                name: item.fileName,
                                url: item.fileUrl,
                                response: { result: item.fileUrl },
                                fileType: 12
                            }
                        ]
                    }
                })
            }
            dialogTitle.value = '编辑'
            isEdit.value = true
            dialogFormVisible.value = true
        })
    })
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await declareMedium({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
getTableData()
const buildList = ref([])

onMounted(() => {
    buildingAll().then(res => {
        buildList.value = res.result
    })
})
const bangongquForm = ref(null)

const enterDialog = async (val) => {
    let declareFile = []
    if (fileList1.value.length > 0) {
        declareFile.push({ fileName: fileList1.value[0].name, fileType: 11, fileUrl: fileList1.value[0].response.result })
    }
    if (fileList2.value.length > 0) {
        declareFile.push({ fileName: fileList2.value[0].name, fileType: 12, fileUrl: fileList2.value[0].response.result })
    }
    form1.value.declareFile = declareFile
    bangongquForm.value.validate(async (valid) => {
        if (valid) {
            form1.value.submitStatus = val
            let res
            if (isEdit.value) {
                res = await applyEdit(form1.value)
            } else {
                res = await declareMediumApply(form1.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : val == 1 ? '申报成功' : '保存成功'
                })
                getTableData()
            }
            initForm()
            dialogFormVisible.value = false
        }
    })
}

const onSubmit = () => {
    page.value = 1
    getTableData()
}
const onReset = () => {
    page.value = 1
    searchInfo.value = {
        buildingName: '',
        name: '',
        type: 3
    }
    getTableData()
}

function downloadTable() {

}
let dialogVisible = ref(false)
let dialogImageUrl = ref()

//图片预览
const handlePicturePreview = (file, files) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true
}

const fileList1 = ref([])
const fileList2 = ref([])

function uploadSuccess1(res) {
    if (res.code != 200) {
        ElMessage({
            type: 'warning',
            message: res.message
        })
        fileList1.value = []
    }
    bangongquForm.value.validateField('bgq')
}
function uploadSuccess2(res) {
    if (res.code != 200) {
        ElMessage({
            type: 'warning',
            message: res.message
        })
        fileList2.value = []
    }
    bangongquForm.value.validateField('bgh')
}
const dialog3 = ref(false)
const fjList = ref([])
function seeFile(id) {
    declareMediumFile(id).then(res => {
        fjList.value = res.result
        dialog3.value = true
    })
}
function handleClose3() {
    dialog3.value = false
}
function closeDialog3() {
    dialog3.value = false
}

const download = async (row) => {
    window.open(row.fileUrl)
}

const detailVisible = ref(false)
function handleCloseDetail() {
    detailVisible.value = false
}
const form2 = ref({})
function seeDetail(row) {
    declareMediumDetail(row.id).then(res => {
        form2.value = row
        form2.value.checkOptions = res.result.map(item => item.checkOptionId)
        form2.value.declareDetail = res.result
        detailVisible.value = true
    })
}
</script>

<style lang="scss">
.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.section-title {
    font-weight: bold;
    font-size: 18px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.sb-draw {
    .title {
        font-size: 16px;
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
    }
}
</style>